class Group < ActiveRecord::Base
  # Relations
  has_and_belongs_to_many :users
  has_many                :uploads,
                          :dependent => :destroy
  belongs_to              :owner,
                          :class_name => 'User',
                          :foreign_key => 'owner_id'
  belongs_to              :teaching
  
  # Validations
  validates_presence_of   :name, :owner_id, :teaching_id
  validates_not_zero      :owner_id, :teaching_id
  validates_uniqueness_of :name, :owner_id,
                          :scope => :teaching_id
  
  # Returns wether or not user is member of the group
  #
  def is_member?(user)
    user = user.id if user.is_a?(User)
    return true if self.owner_id == user
    self.users.count(:id, :conditions => {:id => user}) > 0
  end
  
  # Returns wether or not user is owner of the group
  #
  def is_owner?(user)
    user = user.id if user.is_a?(User)
    self.owner_id == user.to_i
  end
end
